#include "bsp_aht21_driver.h"
#include "bsp_delay.h"
#include "bsp_iic.h"
#include "stdio.h"

// PB13 --> SCL
// PB14 --> SDA

void test_iic()
{
    iic_init();

    uint8_t temp;
    iic_read_bytes(0x71, &temp, 1);

    while (1) {
        Delay_ms(1000);
        uint8_t write_data[3] = {0xac, 0x33, 0x00};
        iic_write_bytes(0x70, write_data, 3);

        Delay_ms(100);
        uint8_t read_data[7] = {0x00};
        iic_read_bytes(0x70, read_data, 7);

        uint32_t sRH = 0;
        sRH = (sRH | read_data[1]) << 8;
        sRH = (sRH | read_data[2]) << 8;
        sRH = (sRH | read_data[3]) >> 4;
        float humidity = (sRH / 1048576.f) * 100;
        printf("Humidity is %f%%\r\n", humidity);

        uint32_t sT = 0;
        sT = (sT | read_data[3]) << 8;
        sT = (sT | read_data[4]) << 8;
        sT = (sT | read_data[5]) & 0xfffff;
        float temprature = (sT / 1048576.f) * 200 - 50;
        printf("Temprature is %f\r\n", temprature);
    }
}

static void enable_irq()
{
    __enable_irq();
}

static void disable_irq()
{
    __disable_irq();
}

void test_aht21()
{
    static aht21_driver_input_func driver_input_func = {
        .pf_iic_init = iic_init,
        .pf_iic_deinit = iic_deinit,
        .pf_iic_read_bytes = iic_read_bytes,
        .pf_iic_write_bytes = iic_write_bytes,

        .pf_disable_irq = disable_irq,
        .pf_enable_irq = enable_irq,

        .pf_delay_ms = HAL_Delay,
    };

    static aht21_type aht21;
    aht21_construct(&aht21, &driver_input_func);

    aht21.pf_aht21_init(&aht21);

    while (1) {
        HAL_Delay(1000);
        uint8_t res = aht21.pf_aht21_getTempAndHumi(&aht21);
        if (res == 0) {
            float temprature = aht21.temprature;
            float humidity = aht21.humidity;
            printf("This is a test for aht21_test.c\r\n");
            printf("Temprature is %f\r\n", temprature);
            printf("Humidity is %f%%\r\n\r\n", humidity);
        }
    }
}
